﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Test.Model;

namespace Test.DAL
{
    public class BaseDAL<T> where T : BaseEntity
    {
        private static Model1 _model = null;
        /// <summary>
        /// 数据上下文
        /// </summary>
        public Model1 Model
        {
            get
            {
                return new Model1();
                //if (_model == null)
                //{
                //    _model = new Model1();
                //}
                //return _model;

            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="Expression">表达式</param>
        /// <returns>List集合</returns>
        public List<T> Select(Expression<Func<T, bool>> expression)
        {

            return Model.Set<T>().Where(expression).ToList();
        }
        /// <summary>
        /// 查询单个对象
        /// </summary>
        /// <param name="Expression">表达式</param>
        /// <returns>单个对象或null</returns>
        public T Single(Expression<Func<T, bool>> expression)
        {

            return Model.Set<T>().FirstOrDefault(expression);
        }
        /// <summary>
        /// 查询单个对象
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>单个对象或null</returns>
        public T Single(int id)
        {
            //model.ClassInfoes.FirstOrDefault(p => p.Id == id)
            return Model.Set<T>().Find(id);//FirstOrDefault LastOrDefault

        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="info">数据</param>
        /// <returns>受影响行数</returns>
        public int Insert(T info)
        {
            var model = Model;
            model.Set<T>().Add(info);
            return model.SaveChanges();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="info">数据</param>
        /// <returns>受影响行数</returns>
        public int Delete(T info)
        {

            var model = Model;
            //Model.Set<T>().Remove(info);
            var temp = model.Set<T>().FirstOrDefault(P => P.Id == info.Id);
            model.Set<T>().Remove(temp);
            //var model = Model;
            //Model.Entry<T>(info).State = System.Data.Entity.EntityState.Deleted;
            return model.SaveChanges();
            

        }



    }
}
